package com.ruoyi.common.utils.bean;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

/**
 * bean对象属性验证
 *
 * @author ruoyi
 */
public class BeanValidators {
    /**
     * 使用指定的验证器对对象进行属性验证，如果验证失败则抛出约束违反异常
     *
     * @param validator 验证器实例，用于执行验证操作
     * @param object 待验证的对象
     * @param groups 验证组，指定要应用的验证规则分组
     * @throws ConstraintViolationException 当对象属性不满足验证约束时抛出此异常
     */
    public static void validateWithException(Validator validator, Object object, Class<?>... groups)
            throws ConstraintViolationException {
        // 执行验证操作，获取约束违反集合
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        // 如果存在约束违反情况，则抛出约束违反异常
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }
}

